#include "stdafx.h"
#include "parse-arguments.h"
#include "../stl-ext/map-ext.h"

void parse_arguments::registerHelpDoc(const tchar *doc)
{
    helpdoc = tstring(doc);
}

bool parse_arguments::parse(int argc, tchar** argv) {
    errmsg.clear();
    for (int i=1; i<argc; i++) {
        tchar* n = argv[i];
        while (*n == _T('-'))
            n++;

        tchar* argname = n;
        if (*argname == 0)
            errmsg.push_back( _T("The '-' char followed nothing.") );
        else {
            tchar* assign = argname;
            while ( *assign != 0 && !::isspace( *assign ) ) {
                if ( *assign == _T('=') ) {
                    tstring name( argname, assign-argname );
                    tstring value( assign+1 );
                    if ( map_contains( nv, name ) )
                        errmsg.push_back( _T("Param ") + name + _T(" was duplicated.") );
                    if ( value.empty() )
                        errmsg.push_back( _T("Param ") + name + _T("'s value is empty.") );
                    nv[ name ] = value;
                    break;
                }
                assign++;
            }
            if ( *assign == 0 || ::isspace( *assign ) )
                nv[ tstring( argname ) ] = _T("");
        }
    }
    return errmsg.empty();
}

bool parse_arguments::contains( tchar argname ) const {
    return map_contains( nv, tstring( 1, argname ) );
}

bool parse_arguments::contains( const tchar* argname ) const {
    return map_contains( nv, tstring( argname ) );
}

const tchar*  parse_arguments::argval( tchar argname ) const {
    StrNVMap::const_iterator iter = nv.find( tstring( 1, argname ) );
    if ( iter != nv.end() )
        return iter->second.c_str();
    return NULL;
}

const tchar* parse_arguments::argval( const tchar* argname ) const {
    StrNVMap::const_iterator iter = nv.find( tstring( argname ) );
    if ( iter != nv.end() )
        return iter->second.c_str();
    return NULL;
}

tstring parse_arguments::error_msg() const {
    tstring msg;
    std::vector<tstring>::const_iterator iter = errmsg.begin();
    for (; iter != errmsg.end(); iter++) {
        msg.append( *iter );
        msg.append( _T("\n") );
    }
    return msg;
}

void parse_arguments::echoargs( tostream& out ) const {
    StrNVMap::const_iterator iter = nv.begin();
    for (; iter != nv.end(); iter++) {
        out << _T("key: [") << iter->first << _T("] value: [") << iter->second << _T("]") << std::endl;
    }
}


